import {Component, OnDestroy, OnInit} from '@angular/core';
import {MsgConstants} from '../../../constants/constants';
import {TableUtil} from '../../../util/table-util';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {ActivatedRoute, Router} from '@angular/router';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgResult} from '../../../models/msg-result';
import {Observable} from 'rxjs/Observable';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {DaAPI, DaChartColor, DaChartTitle, DaFactorName} from '../da-constants';
import {DaTraitService} from './da-trait.service';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-trait',
  templateUrl: './da-trait.component.html',
  styleUrls: ['./da-trait.component.css']
})
export class DaTraitComponent implements OnInit, OnDestroy {
  config;
  pointType = 'skyEyeSite'; // 点位类型
  factor = 'PM2_5';
  timeDataType = 'hourData';
  timeDataFormat = 'YYYY-MM-DD HH:00:00';
  siteCode = '';
  rangeCode = '';
  siteArr: Array<any> = [];
  nationCode = '';
  scatterObj: any;
  chartOption: object;
  colorArr: Array<any> = [];
  isLoading = true;
  resizeEnent: any;
  timeDataArr: Array<any> = [];
  table: any;
  startDate = new Date(moment().subtract(1, 'M').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();

  componentArr: Array<any> = [];

  chartObjArr: Array<any> = [];
  compareDataArr: Array<any> = [
    {compareComOne: '', compareComTwo: ''},
    {compareComOne: '', compareComTwo: ''},
    {compareComOne: '', compareComTwo: ''},
    {compareComOne: '', compareComTwo: ''}
  ];
  vocsData: any = {};

  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private response: ResponseUtil,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private traitService: DaTraitService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('活性水平', '');
    this.pageSubject.pushPage('特征组分分析', '查询');
  }

  initData = () => {
    this.timeDataArr = [
      {'name': '小时', dataType: 'hourData', formatter: 'YYYY-MM-DD HH:00', mode: 'day', format: 'YYYY-MM-DD HH:00:00'},
      {'name': '日', dataType: 'dayData', formatter: 'YYYY-MM-DD', mode: 'day', format: 'YYYY-MM-DD 00:00:00'},
      {'name': '月', dataType: 'monthData', formatter: 'YYYY-MM', mode: 'month', format: 'YYYY-MM-01 00:00:00'},
      {'name': '年', dataType: 'yearData', formatter: 'YYYY', mode: 'month', format: 'YYYY-01-01 00:00:00'}
    ];
    const scatterObj = echarts.init(document.getElementById('traitCom'));
    const scatterObj2 = echarts.init(document.getElementById('traitCom2'));
    const scatterObj3 = echarts.init(document.getElementById('traitCom3'));
    const scatterObj4 = echarts.init(document.getElementById('traitCom4'));
    this.chartObjArr.push(scatterObj, scatterObj2, scatterObj3, scatterObj4);
    this.colorArr = [
      '#1890FF', '#2FC25B', '#FACC14', '#8543E0', '#13C2C2', '#3436c7',
      '#531DAB', '#2F54EB', '#40A9FF', '#5CDBD3', '#B7EB8F', '#FFE58F',
      '#FFC069', '#FF7A45'];
  };
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        this.chartObjArr.forEach(val => val.resize())
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  search(i) {
    if (this.startDate > this.endDate) {
      if (this.startDate > this.endDate) {
        this.dialogService.info('开始时间大于结束时间，请重新选择');
      }
    } else {
      this.isLoading = true;
      this.vocsData.factor = [this.compareDataArr[i].compareComOne, this.compareDataArr[i].compareComTwo];
      // this.barRender(this.vocsData, chartObj);
      this.getFeatureData(i);
    }
  }
  /**
   * 柱状图
   * @param data
   * @param i
   */
  private barRender = (data, i) => {
    const scatterData = this.getLineData(data.dataList, data.linear.k, data.linear.b);
    console.log(scatterData);
    const markLineOpt = {
      animation: false,
      silent: true,
      label: {
        // formatter: 'y = 1.3703 * x + 1.8247 \n R² = 0.1568',
        textStyle: {
          align: 'right'
        }
      },
      lineStyle: {
        normal: {
          color: DaChartColor.PM25Color,
          type: 'dashed'
        }
      },
      data: [[{
        coord: scatterData.scatterArr[0],
        symbol: 'none'
      }, {
        coord: scatterData.scatterArr[1],
        symbol: 'none'
      }]]
    };
    const compareChart = this.chartObjArr[i];
    const componentOne = data.nameList[0] || '';
    const componentTwo = data.nameList[1] || '';
    // 图表配置信息
    const option = {
      title : {
        text: componentOne + '与' + componentTwo + DaChartTitle.daTraitTitle,
        left: 'center'
      },
      tooltip: {
        formatter: '{c}'
      },
      grid: [{
        top: 40
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        name: componentOne || '',
        nameLocation: 'center',
        nameGap: 30,
        nameTextStyle: {
          fontSize: 14
        },
        min: scatterData.xDataObj.xMinData, max: scatterData.xDataObj.xMaxData
      },
      yAxis: {
        name: componentTwo || '',
        nameLocation: 'center',
        nameGap: 40,
        nameTextStyle: {
          fontSize: 14
        },
        min: scatterData.yDataObj.yMinData, max: scatterData.yDataObj.yMaxData
      },
      series: [{
        name: 'line',
        data: data.dataList,
        type: 'scatter',
        markLine: markLineOpt
      }, {
        name: 'line',
        data: [],
        type: 'line',
        markLine: {
          animation: false,
          silent: true,
          label: {
            formatter: 'y = ' + (data.linear.k || '-') + ' * x ' + (data.linear.b < 0 ?  '-' : '+') + (Math.abs(data.linear.b) || '-') + '  \n R² = ' + (data.linear.r || '-') + '  ',
            color: DaChartColor.PM25Color,
            textStyle: {
              align: 'right'
            }
          },
          lineStyle: {
            normal: {
              color: 'transparent',
              type: 'dashed'
            }
          },
          data: [[{
            coord: [scatterData.xDataObj.xMinData, scatterData.yDataObj.yMinData],
            symbol: 'none'
          }, {
            coord: [Math.ceil(scatterData.xDataObj.xMaxData), scatterData.yDataObj.yMaxData],
            y: 55,
            x: '90%',
            symbol: 'none'
          }]]
        }
      }]
    };
    compareChart.setOption(option, {notMerge: true});
  };
  /**
   * 获取YAxis最大最小值
   * @param dataArr
   */
  getYMinAndMaxData = (dataArr) => {
    let yMaxData = 10, yMinData = 0;
    if (dataArr.length > 0) {
      yMaxData = Math.ceil(Math.max(...dataArr));
      // yMinData = Math.floor(Math.min(...dataArr) * 100) / 100;
    }
    return {yMaxData: yMaxData, yMinData: yMinData}
  };
  /**
   *
   * 获取XAxis最大最小值
   * @param dataArr
   */
  getXMinAndMaxData = (dataArr) => {
    let xMaxData = 10, xMinData = 0;
    if (dataArr.length > 0) {
      xMaxData = Math.ceil(Math.max(...dataArr));
    }
    return {xMaxData: xMaxData, xMinData: xMinData}
  };
  /**
   * 获取辅助线起始点数据
   * @param scatterData
   * @param k
   * @param b
   */
  getLineData = (scatterData, k , b) => {
    const dataARR = [[], []];
    scatterData.forEach((val) => {
      if (!isNaN(val[0])) {
        dataARR[0].push(val[0])
      }
      if (!isNaN(val[1])) {
        dataARR[1].push(val[1])
      }
    });
    const yDataObj = this.getYMinAndMaxData(dataARR[1]);
    const xDataObj = this.getXMinAndMaxData(dataARR[0]);
    const lineData = k * xDataObj.xMaxData + b;
    const scatterArr = [[], []];
    if (b < 0) {
      const x = Math.abs(b) / k;
      scatterArr[0] = [x, 0]
    } else {
      scatterArr[0] = [0, b];
    }
    if (lineData < 0) {
      const x =  0 - b / k;
      scatterArr[1] = [x, 0]
    } else {
      if (yDataObj.yMaxData < lineData) {
        yDataObj.yMaxData = Math.ceil(lineData);
      }
      scatterArr[1] = [xDataObj.xMaxData, lineData];
    }
    return {yDataObj: yDataObj, xDataObj: xDataObj, scatterArr: scatterArr};
  };
  /**
   * 时间类型切换
   * @param timeData
   */
  timeDataChange(timeData) {
    if (this.timeDataType === timeData.dataType) {
      return false;
    }
    this.timeDataType = timeData.dataType;
    this.timeDataFormat = timeData.format;
    this.changeStartAndEndDate();
    this.search(0);
    this.search(1);
    this.search(2);
    this.search(3);
  }
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  get timeFormatter() {
    let formatter = 'YYYY-MM-DD';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        formatter = val.formatter;
      } else {
        return true;
      }
    });
    return formatter;
  }
  get timeMode() {
    let dataMode = 'day';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        dataMode = val.mode;
      } else {
        return true;
      }
    });
    return dataMode;
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.traitService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getTrait();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };

  /**
   * 获取vocs分类数据
   */
  getTrait = () => {
    this.traitService.getVocComData().subscribe(
      result => this.responseUtil.success(result, this.handleClass),
      error => this.responseUtil.error(error)
    )
  };
  handleClass = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.componentArr = result.data;
        this.compareDataArr = [
          {compareComOne: this.componentArr[0].value, compareComTwo: this.componentArr[1].value},
          {compareComOne: this.componentArr[2].value, compareComTwo: this.componentArr[3].value},
          {compareComOne: this.componentArr[4].value, compareComTwo: this.componentArr[5].value},
          {compareComOne: this.componentArr[6].value, compareComTwo: this.componentArr[7].value}
        ];
        this.getFeatureData(0);
        this.getFeatureData(1);
        this.getFeatureData(2);
        this.getFeatureData(3);
      }
    } else {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 获取图表数据
   */
  getFeatureData(i) {
    const dataObj = {
      siteCode: this.siteCode,
      rangeCode: this.rangeCode,
      dataType: this.timeDataType,
      factors: this.compareDataArr[i].compareComOne + '|' + this.compareDataArr[i].compareComTwo,
      startTime : this.startDate ? moment(this.startDate).format(this.timeDataFormat) : '',
      endTime : this.endTime
    };
    this.traitService.getFeatureData(dataObj).subscribe(
      result => this.response.success(result, () => {
        this.handleO3data(result, i)
      }),
      error => this.response.error(error)
    );
  }
  handleO3data = (result: MsgResult, i) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.dataList) {
        if (result.data.linear.k) {
          this.barRender(result.data, i);
        } else {
          result.data.linear = {
            k: 0,
            b: 0,
            r: 0
          };
          this.barRender(result.data, i);
        }
      } else {
        this.barRender({
          nameList: [],
          dataList: [],
          linear: {
            k: 0,
            b: 0,
            r: 0
          }
        }, i);
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  get endTime () {
    let endDate = '';
    const daysInMonth = moment(this.endDate, "YYYY-MM").daysInMonth();
    if (this.endDate) {
      if (this.timeDataType === 'yearData') {
        endDate = moment(this.endDate).format('YYYY-12-31 23:59:59')
      } else if (this.timeDataType === 'monthData') {
        endDate = moment(this.endDate).format('YYYY-MM-' + daysInMonth +' 23:59:59')
      } else if (this.timeDataType === 'dayData') {
        endDate = moment(this.endDate).format('YYYY-MM-DD 23:59:59')
      } else {
        endDate = moment(this.endDate).format('YYYY-MM-DD HH:59:59')
      }
    }
    return endDate;
  }
}
